//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using DotNetNuke.Application;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Security;
using DotNetNuke.Services.Installer;
using DotNetNuke.Services.Installer.Packages;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Modules;
using DotNetNuke.UI.WebControls;
namespace DotNetNuke.Modules.Admin.Extensions
{
	partial class Extensions : ModuleUserControlBase, Entities.Modules.IActionable
	{
		private string _Mode = "All";
		public string PackageType {
			get { return cboPackageTypes.SelectedValue; }
		}
		public string Mode {
			get {
				if (ModuleContext.Settings.ContainsKey("Extensions_Mode") 
					&& !string.IsNullOrEmpty(ModuleContext.Settings["Extensions_Mode"].ToString())) {
					_Mode = ModuleContext.Settings["Extensions_Mode"].ToString();
				}
				return _Mode;
			}
		}
		protected string GetIsPackageInUseInfo(object dataItem)
		{
			if ((dataItem is PackageInfo)) {
				PackageInfo package = (PackageInfo)dataItem;
				if ((package.PackageType.ToUpper() == "MODULE")) {
					if ((PackagesInUse.ContainsKey(package.PackageID))) {
						return "<a href=\"" + ModuleContext.EditUrl("PackageID", package.PackageID.ToString(), "UsageDetails") + "\">Yes</a>";
					} else {
						return "No";
					}
				}
			}
			return string.Empty;
		}
		private void AddModulesToList(List<PackageInfo> packages)
		{
			Dictionary<int, PortalDesktopModuleInfo> portalModules = DesktopModuleController.GetPortalDesktopModulesByPortalID(this.ModuleContext.PortalId);
			foreach (PackageInfo modulePackage in PackageController.GetPackagesByType(Null.NullInteger, "Module")) {
				DesktopModuleInfo desktopModule = DesktopModuleController.GetDesktopModuleByPackageID(modulePackage.PackageID);
				foreach (PortalDesktopModuleInfo portalModule in portalModules.Values) {
					if (desktopModule != null && portalModule.DesktopModuleID == desktopModule.DesktopModuleID) {
						packages.Add(modulePackage);
					}
				}
			}
		}
		private void BindGrid()
		{
			List<PackageInfo> packages = new List<PackageInfo>();
			switch (Mode) {
				case "All":
					if (String.IsNullOrEmpty(PackageType)) {
						packages = PackageController.GetPackages(Null.NullInteger);
					} else {
						switch (PackageType) {
							case "Module":
								if (!this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab) {
									AddModulesToList(packages);
								} else {
									packages = PackageController.GetPackagesByType(Null.NullInteger, "Module");
								}
								break;
							case "Skin":
							case "Container":
								if (this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab) {
									packages = PackageController.GetPackagesByType(Null.NullInteger, PackageType);
								} else {
									packages = PackageController.GetPackagesByType(this.ModuleContext.PortalId, PackageType);
								}
								break;
							default:
								packages = PackageController.GetPackagesByType(Null.NullInteger, PackageType);
								break;
						}
					}
					break;
				case "LanguagePack":
					packages = PackageController.GetPackagesByType(Null.NullInteger, "CoreLanguagePack");
					packages.AddRange(PackageController.GetPackagesByType(Null.NullInteger, "ExtensionLanguagePack"));
					break;
				case "Module":
					if (this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab) {
						packages = PackageController.GetPackagesByType(Null.NullInteger, "Module");
					} else {
						AddModulesToList(packages);
					}
					grdExtensions.DataSource = packages;
					break;
				case "Skin":
					packages = PackageController.GetPackagesByType(Null.NullInteger, "Skin");
					packages.AddRange(PackageController.GetPackagesByType(Null.NullInteger, "Container"));
					break;
			}
			if (packages.Count > 0) {
				lblNoResults.Visible = false;
				grdExtensions.Visible = true;
				grdExtensions.DataSource = packages;
				grdExtensions.DataBind();
			} else {
				grdExtensions.Visible = false;
				lblNoResults.Visible = true;
			}
			if (this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab) {
				switch (Mode) {
					case "LanguagePack":
						trLanguageSelector.Visible = false;
						break;
					default:
						trLanguageSelector.Visible = !Request.IsLocal || (PackageType == "CoreLanguagePack" || PackageType == "ExtensionLanguagePack");
						break;
				}
			} else {
				trLanguageSelector.Visible = false;
			}
		}
		private string UpgradeIndicator(System.Version version, string packageType, string packageName, string culture)
		{
			string strURL = DotNetNuke.Services.Upgrade.Upgrade.UpgradeIndicator(version, packageType, packageName, culture, Request.IsLocal, Request.IsSecureConnection);
			if (String.IsNullOrEmpty(strURL)) {
				strURL = Common.Globals.ApplicationPath + "/images/spacer.gif";
			}
			return strURL;
		}
		private string UpgradeRedirect(System.Version version, string packageType, string packageName, string culture)
		{
			return DotNetNuke.Services.Upgrade.Upgrade.UpgradeRedirect(version, packageType, packageName, culture);
		}
		protected string GetAboutTooltip(object dataItem)
		{
			string returnValue = string.Empty;
			try {
				if ((this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab)) {
					int portalID = Convert.ToInt32(DataBinder.Eval(dataItem, "PortalID"));
					if ((portalID != Null.NullInteger && portalID != int.MinValue)) {
						PortalInfo portal = PortalCtrl.GetPortal(portalID);
						returnValue = string.Format(Localization.GetString("InstalledOnPortal.Tooltip", LocalResourceFile), portal.PortalName);
					} else {
						returnValue = Localization.GetString("InstalledOnHost.Tooltip", LocalResourceFile);
					}
				}
			} catch (Exception ex) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, ex);
			}
			return returnValue;
		}
		protected string FormatVersion(object version)
		{
			PackageInfo package = version as PackageInfo;
			string retValue = Null.NullString;
			if (package != null) {
				retValue = package.Version.ToString(3);
			}
			return retValue;
		}
		protected string GetPackageTypeDescription(string typeKey)
		{
			string returnValue = typeKey;
			if ((PackageTypesList.ContainsKey(typeKey))) {
				returnValue = PackageTypesList[typeKey].Description;
			}
			return returnValue;
		}
		protected override void OnInit(System.EventArgs e)
		{
			base.OnInit(e);
			foreach (DataGridColumn column in grdExtensions.Columns) {
				if (object.ReferenceEquals(column.GetType(), typeof(ImageCommandColumn))) {
					ImageCommandColumn imageColumn = (ImageCommandColumn)column;
					if (!String.IsNullOrEmpty(imageColumn.CommandName)) {
						imageColumn.Text = Localization.GetString(imageColumn.CommandName, this.LocalResourceFile);
					}
					if (imageColumn.CommandName == "Delete") {
						string[] parameters = new string[2];
						parameters[0] = "rtab=" + this.ModuleContext.TabId.ToString();
						parameters[1] = "packageId=KEYFIELD";
						string formatString = Common.Globals.NavigateURL(this.ModuleContext.TabId, "UnInstall", parameters);
						formatString = formatString.Replace("KEYFIELD", "{0}");
						imageColumn.NavigateURLFormatString = formatString;
					}
					if (imageColumn.CommandName == "Edit") {
						string formatString = ModuleContext.EditUrl("PackageID", "KEYFIELD", "Edit");
						formatString = formatString.Replace("KEYFIELD", "{0}");
						imageColumn.NavigateURLFormatString = formatString;
					}
				}
			}
		}
		protected override void OnLoad(System.EventArgs e)
		{
			base.OnLoad(e);

			#region Bind Handles
			cboLocales.SelectedIndexChanged += new EventHandler(cboLocales_SelectedIndexChanged);
			cboPackageTypes.SelectedIndexChanged += new EventHandler(cboPackageTypes_SelectedIndexChanged);
			grdExtensions.ItemCreated += new DataGridItemEventHandler(grdExtensions_ItemCreated);
			grdExtensions.ItemDataBound += new DataGridItemEventHandler(grdExtensions_ItemDataBound);
			#endregion

			if (!Page.IsPostBack) {
				Localization.LocalizeDataGrid(ref grdExtensions, LocalResourceFile);
				if (String.IsNullOrEmpty(DotNetNuke.Services.Upgrade.Upgrade.UpgradeIndicator(DotNetNukeContext.Current.Application.Version, "", "~", "", Request.IsLocal, Request.IsSecureConnection))) {
					lblUpdate.Visible = false;
					grdExtensions.Columns[8].HeaderText = "";
				}
				switch (Mode) {
					case "All":
						cboPackageTypes.DataSource = PackageTypesList.Values;
						cboPackageTypes.DataBind();
						cboPackageTypes.Items.Insert(0, new ListItem(Localization.GetString("Not_Specified", Localization.SharedResourceFile), ""));
						cboPackageTypes.SelectedIndex = 0;
						break;
					case "LanguagePack":
						trPackageType.Visible = false;
						break;
					default:
						trPackageType.Visible = false;
						break;
				}
				cboLocales.DataSource = Localization.GetLocales(Null.NullInteger).Values;
				cboLocales.DataBind();
				cboLocales.Items.Insert(0, new ListItem(Localization.GetString("Not_Specified", Localization.SharedResourceFile), ""));
			}
			BindGrid();
			
		}

		protected override void OnPreRender(System.EventArgs e)
		{
			foreach (DataGridColumn column in grdExtensions.Columns) {
				if (column.HeaderText == "Type") {
					column.Visible = Mode == "Skin";
				}
				if (column.FooterText == "Portal") {
					column.Visible = (this.ModuleContext.IsHostMenu && (Mode == "Skin" || (Mode == "All" && (String.IsNullOrEmpty(PackageType) || PackageType == "Skin" || PackageType == "Container"))));
				}
			}
			base.OnPreRender(e);
		}
		private DataGridItem CreateGridGroupHeader(string title, string paddingTop, object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
			HtmlGenericControl groupHeader = new HtmlGenericControl("div");
			groupHeader.Attributes.Add("class", "Head");
			groupHeader.InnerHtml = title;
			if ((paddingTop == string.Empty)) {
				paddingTop = "5px";
			}
			TableCell cell = new TableCell();
			cell.Controls.Add(groupHeader);
			cell.Controls.Add(new HtmlGenericControl("hr"));
			cell.ColumnSpan = e.Item.Cells.Count;
			cell.HorizontalAlign = HorizontalAlign.Left;
			cell.Style.Add("padding-bottom", "5px");
			cell.Style.Add("padding-top", "20px");
			DataGridItem gridItem = new DataGridItem(e.Item.ItemIndex + 1, 0, ListItemType.Item);
			gridItem.Controls.Add(cell);
			return gridItem;
		}
		public string UpgradeService(System.Version version, string packageType, string packageName)
		{
			string strUpgradeService = "";
			strUpgradeService += "<a title=\"" + Localization.GetString("UpgradeMessage", this.LocalResourceFile) + "\" href=\"" + UpgradeRedirect(version, packageType, packageName, "") + "\" target=\"_new\"><img title=\"" + Localization.GetString("UpgradeMessage", this.LocalResourceFile) + "\" src=\"" + UpgradeIndicator(version, packageType, packageName, "") + "\" border=\"0\" /></a>";
			if (!string.IsNullOrEmpty(cboLocales.SelectedValue)) {
				strUpgradeService += "<br />";
				strUpgradeService += "<a title=\"" + Localization.GetString("LanguageMessage", this.LocalResourceFile) + "\" href=\"" + UpgradeRedirect(version, packageType, packageName, cboLocales.SelectedItem.Value) + "\" target=\"_new\"><img title=\"" + Localization.GetString("LanguageMessage", this.LocalResourceFile) + "\" src=\"" + UpgradeIndicator(version, packageType, packageName, cboLocales.SelectedItem.Value) + "\" border=\"0\" /></a>";
			}
			return strUpgradeService;
		}
		private IDictionary<string, PackageType> _PackageTypes = null;
		protected IDictionary<string, PackageType> PackageTypesList {
			get {
				if ((_PackageTypes == null)) {
					_PackageTypes = new Dictionary<string, PackageType>();
					foreach (PackageType packageType in PackageController.GetPackageTypes()) {
						_PackageTypes.Add(packageType.Type, packageType);
					}
				}
				return _PackageTypes;
			}
		}
		private IDictionary<int, PackageInfo> _PackagesInUse = null;
		protected IDictionary<int, PackageInfo> PackagesInUse {
			get {
				if ((_PackagesInUse == null)) {
					_PackagesInUse = PackageController.GetModulePackagesInUse(PortalController.GetCurrentPortalSettings().PortalId, this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab);
				}
				return _PackagesInUse;
			}
		}
		private PortalController _PortalCtrl = null;
		protected PortalController PortalCtrl {
			get {
				if ((_PortalCtrl == null)) {
					_PortalCtrl = new PortalController();
				}
				return _PortalCtrl;
			}
		}
		protected void cboLocales_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			BindGrid();
		}
		protected void cboPackageTypes_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			BindGrid();
		}
		private string _CurrentGroupKey = string.Empty;
		protected void grdExtensions_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
			if ((String.IsNullOrEmpty(PackageType) && Mode == "All" && e.Item != null && e.Item.DataItem != null)) {
				if ((e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)) {
					string groupTitleKey = DataBinder.Eval(e.Item.DataItem, "PackageType").ToString();
					if ((_CurrentGroupKey != groupTitleKey)) {
						DataGrid grid = (DataGrid)sender;
						Table childTable = (Table)grid.Controls[0];
						childTable.Rows.Add(CreateGridGroupHeader(GetPackageTypeDescription(groupTitleKey), "20px", sender, e));
						_CurrentGroupKey = groupTitleKey;
					}
				}
			}
		}
		protected void grdExtensions_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
			DataGridItem item = e.Item;
			if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem)
			{
				HyperLink editHyperlink = item.Controls[1].Controls[0] as HyperLink;
				if (editHyperlink != null) {
					PackageInfo package = (PackageInfo)item.DataItem;
					if (this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab) {
						if (package.IsSystemPackage) {
							editHyperlink.Visible = false;
						} else {
							editHyperlink.Visible = PackageController.CanDeletePackage(package, ModuleContext.PortalSettings);
						}
					} else {
						editHyperlink.Visible = false;
					}
				}
				editHyperlink = item.Controls[0].Controls[0] as HyperLink;
				if (editHyperlink != null) {
					editHyperlink.Visible = this.ModuleContext.IsEditable;
				}
			}
			if (String.IsNullOrEmpty(PackageType) && Mode == "All") {
				if (e.Item.ItemIndex == 0) {
					DataGridItem row = new DataGridItem(0, 0, ListItemType.Item);
					TableCell cell1 = new TableCell();
					cell1.Text = "";
					row.Cells.Add(cell1);
					TableCell cell2 = new TableCell();
					cell2.Text = "";
					row.Cells.Add(cell2);
					TableCell cell4 = new TableCell();
					if (String.IsNullOrEmpty(Localization.GetString("AppTitle", this.LocalResourceFile))) {
						cell4.Text = DotNetNukeContext.Current.Application.Title;
					} else {
						cell4.Text = Localization.GetString("AppTitle", this.LocalResourceFile);
					}
					row.Cells.Add(cell4);
					TableCell cell5 = new TableCell();
					string appType = Localization.GetString("AppType", this.LocalResourceFile);
					if ((appType == string.Empty)) {
						appType = DotNetNukeContext.Current.Application.Type;
					}
					cell5.Text = appType;
					row.Cells.Add(cell5);
					TableCell cell6 = new TableCell();
					cell6.Text = "";
					row.Cells.Add(cell6);
					TableCell cell7 = new TableCell();
					if (String.IsNullOrEmpty(Localization.GetString("AppDescription", this.LocalResourceFile))) {
						cell7.Text = DotNetNukeContext.Current.Application.Description;
					} else {
						cell7.Text = Localization.GetString("AppDescription", this.LocalResourceFile);
					}
					row.Cells.Add(cell7);
					TableCell cell8 = new TableCell();
					cell8.Text = DotNetNukeContext.Current.Application.Version.ToString(3);
					row.Cells.Add(cell8);
					TableCell cell9 = new TableCell();
					cell9.Text = UpgradeService(DotNetNukeContext.Current.Application.Version, DotNetNukeContext.Current.Application.Type, DotNetNukeContext.Current.Application.Name);
					row.Cells.Add(cell9);
					grdExtensions.Controls[0].Controls.AddAt(1, row);
					grdExtensions.Controls[0].Controls.AddAt(1, CreateGridGroupHeader(appType, "", sender, e));
				}
			}
		}
		public ModuleActionCollection ModuleActions {
			get {
				ModuleActionCollection Actions = new ModuleActionCollection();
				switch (Mode) {
					case "All":
						Actions.Add(ModuleContext.GetNextActionID(), Services.Localization.Localization.GetString("ExtensionInstall.Action", LocalResourceFile), ModuleActionType.AddContent, "", "action_import.gif", Util.InstallURL(ModuleContext.TabId, ""), false, SecurityAccessLevel.Host, true, false);
						if (this.ModuleContext.IsHostMenu) {
							Actions.Add(ModuleContext.GetNextActionID(), Services.Localization.Localization.GetString("CreateExtension.Action", LocalResourceFile), ModuleActionType.AddContent, "", "add.gif", ModuleContext.EditUrl("NewExtension"), false, SecurityAccessLevel.Host, true, false);
						}
						if (this.ModuleContext.IsHostMenu) {
							Actions.Add(ModuleContext.GetNextActionID(), Services.Localization.Localization.GetString("InstallExtensions.Action", LocalResourceFile), ModuleActionType.AddContent, "", "action_import.gif", ModuleContext.EditUrl("BatchInstall"), false, SecurityAccessLevel.Host, true, false);
						}
						break;
					case "LanguagePack":
						Actions.Add(ModuleContext.GetNextActionID(), Services.Localization.Localization.GetString("LanguagePackInstall.Action", LocalResourceFile), ModuleActionType.AddContent, "", "action_import.gif", Util.InstallURL(ModuleContext.TabId, ""), false, SecurityAccessLevel.Host, true, false);
						Actions.Add(ModuleContext.GetNextActionID(), Services.Localization.Localization.GetString("CreateLanguagePack.Action", LocalResourceFile), ModuleActionType.AddContent, "", "add.gif", ModuleContext.EditUrl("Type", "LanguagePack", "NewExtension"), false, SecurityAccessLevel.Host, true, false);
						break;
					case "Module":
						Actions.Add(ModuleContext.GetNextActionID(), Services.Localization.Localization.GetString("ModuleInstall.Action", LocalResourceFile), ModuleActionType.AddContent, "", "action_import.gif", Util.InstallURL(ModuleContext.TabId, ""), false, SecurityAccessLevel.Host, true, false);
						Actions.Add(ModuleContext.GetNextActionID(), Services.Localization.Localization.GetString("CreateModule.Action", LocalResourceFile), ModuleActionType.AddContent, "", "add.gif", ModuleContext.EditUrl("Type", "Module", "EditModuleDefinition"), false, SecurityAccessLevel.Host, true, false);
						break;
					case "Skin":
						Actions.Add(ModuleContext.GetNextActionID(), Services.Localization.Localization.GetString("SkinInstall.Action", LocalResourceFile), ModuleActionType.AddContent, "", "action_import.gif", Util.InstallURL(ModuleContext.TabId, ""), false, SecurityAccessLevel.Host, true, false);
						Actions.Add(ModuleContext.GetNextActionID(), Services.Localization.Localization.GetString("CreateSkin.Action", LocalResourceFile), ModuleActionType.AddContent, "", "add.gif", ModuleContext.EditUrl("Type", "Skin", "NewExtension"), false, SecurityAccessLevel.Host, true, false);
						Actions.Add(ModuleContext.GetNextActionID(), Services.Localization.Localization.GetString("CreateContainer.Action", LocalResourceFile), ModuleActionType.AddContent, "", "add.gif", ModuleContext.EditUrl("Type", "Container", "NewExtension"), false, SecurityAccessLevel.Host, true, false);
						break;
				}
				return Actions;
			}
		}
	}
}
